package com.gopay.common.log.collect;

import com.gopay.common.log.annotation.LogX;
import com.gopay.common.log.aop.LogAopAdviceComponent;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * 日志不走AOP代理类
 *
 * @LogNoAopProxy.java
 * @author dak.wang
 * @2016年4月20日 下午3:18:55 www.gopay.com.cn Inc.All rights reserved.
 */
public class LogNoAopProxy {
    @Autowired
    private LogAopAdviceComponent logAopAdviceComponent;

	private static Logger errorlogger = Logger.getLogger(LogNoAopProxy.class);
	
    private Object target;
    private String methodName;
    private Class[] argTypes;
    private Object[] args;

    public LogNoAopProxy(Object target, String methodName, Class[] argTypes, Object[] args) {
        this.target = target;
        this.methodName = methodName;
        this.argTypes = argTypes;
        this.args = args;
    }

    public Object invoke() throws Exception {
    	LogBag logBag = new LogBag();
    	String bagId = null;
    	
    	Method method = null;
        try{
            method = target.getClass().getDeclaredMethod(methodName, argTypes);
        	bagId = UUID.randomUUID().toString();
            logBag.setId(bagId);
            // before
            Annotation ann = method.getAnnotation(com.gopay.common.log.annotation.LogX.class);
            if (ann != null) {
                LogX logx = (LogX) ann;
                /**** modify by sh.jiao 20170524 修改logX注解 start****/
	            /*logBag.setPlatform(logx.platform().value);
	            logBag.setCategory(logx.category().value);*/
                String operTypeCd = logx.operTypeCd();
                logBag.setPlatform(operTypeCd.substring(0,2));
                logBag.setCategory(operTypeCd.substring(2,4));
                logBag.setModules(operTypeCd.substring(4,6));
                logBag.setOperTypeCd(logx.operTypeCd());
                /**** modify by sh.jiao 20170524 修改logX注解 end****/
            }
        }catch(Exception e){
        	errorlogger.error("invoke方法抛出异常",e);
        }

        try {
            logAopAdviceComponent.beforeAdvice(logBag);
            //LogAopAdviceUtil.beforeAdvice(logBag);

            Object result = method.invoke(target, args);

            // afterReturnning
            //LogAopAdviceUtil.afterReturningAdvice(bagId);
            logAopAdviceComponent.afterReturningAdvice(bagId);

            return result;
        } catch (Exception e) {
            // afterThrowing
            //LogAopAdviceUtil.afterThrowingAdvice(bagId, e);
            logAopAdviceComponent.afterThrowingAdvice(bagId, e);

            throw e;
        }
    }

}
